package logic

import (
	"errors"
	"myself/db/managers"
	"myself/db/models"
	"myself/util"
)

type AccountLogic struct {
	tableName string
}

func NewAccountLogic() *AccountLogic {
	return &AccountLogic{tableName: "account"}
}

const tableName = "account"

func (AccountLogic) HasAccountByAccountId(accountId string) bool {
	var count int64
	accountManager, err := managers.NewAccountManger()
	if err != nil {
		return true
	}
	accountManager.Conn.Table(tableName).Where("account_id = ?", accountId).Count(&count)
	if count > 0 {
		return true
	}
	return false
}

func (AccountLogic) CreateAccount(accountId string, password string, realName string) error {
	accountManager, err := managers.NewAccountManger()
	if err != nil {
		return err
	}
	err = accountManager.Conn.Table(tableName).Create(&models.Account{AccountId: accountId, Password: password, RealName: realName}).Error
	return err
}

func (AccountLogic) Login(accountId string, password string) (string, error) {
	var count int64
	accountManager, err := managers.NewAccountManger()
	if err != nil {
		return "", err
	}
	accountManager.Conn.Table(tableName).Where("account_id = ? and password = ?", accountId, password).Count(&count)
	if count > 0 {
		return util.GenerateToken(accountId)
	}
	return "", errors.New("账户不存在")
}
